//
//  LRParallaxBackground.m
//  lineRunner_cocos2d
//
//  Created by chen jingsen on 13-1-17.
//  Copyright 2013年 __MyCompanyName__. All rights reserved.
//

#import "LRParallaxBackground.h"


@implementation LRParallaxBackground

- (id)init
{
    if (self = [super init]) {
        [self LR_initBackground];
        [self scheduleUpdate];
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)LR_initBackground
{
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    
    //加入背景
    CCSprite *backGround = [CCSprite spriteWithFile:@"background.png"];
    [backGround setPosition:CGPointMake(screenSize.width*0.5, screenSize.height*0.5)];
    [self addChild:backGround z:-1];
    
    CCTexture2D* gameArtTexture = [[CCTextureCache sharedTextureCache] addImage:@"gElem.png"];
    spriteBatch = [CCSpriteBatchNode batchNodeWithTexture:gameArtTexture];
    [self addChild:spriteBatch];
    
    CCSpriteFrameCache *frameCache = [CCSpriteFrameCache sharedSpriteFrameCache];
    [frameCache addSpriteFramesWithFile:@"gElem.plist"];
    for (int i = 1; i <= 3; i++) {
        NSString* file = [NSString stringWithFormat:@"skyline%d.png",i];
        CCSpriteFrame *frame = [frameCache spriteFrameByName:file];
        CCSprite *sprit = [CCSprite spriteWithSpriteFrame:frame];
        sprit.position =CGPointMake(sprit.textureRect.size.width*(i-1),sprit.textureRect.size.height*0.5);
        
        parallaxWith += sprit.textureRect.size.width;
        sprit.anchorPoint  = CGPointMake(0.0f, 0.5f);
        [spriteBatch addChild:sprit];
    }
}

-(void) update:(ccTime)delta
{
    CCSprite *sprite;
    CCARRAY_FOREACH([spriteBatch children], sprite)
    {
        CGPoint point =  sprite.position;
        point.x = point.x-delta*20;
        if (point.x < -sprite.textureRect.size.width) {
            point.x = parallaxWith - sprite.textureRect.size.width;
        }
        sprite.position = point;
    }
}

@end
